const fs = require('fs')
const path = require('path')

const utils = require(process.cwd() + '/src/utils/index')
const config = require(process.cwd() + '/src/config/config')
const autotilesOptions = require(process.cwd() + '/src/config/autotilesOptions')

const Tile = require('./tile')

// 默认动画固定为4帧
const DEFAULT_ANIMATION_FRAME_NUM = 4

class Autotile extends Tile {
  constructor (autotile) {
    super()
    this.initAutotile(autotile)
  }
  
  // 初始化空的Autotile对象
  initAutotile (autotile) {    
    // 初始化
    this.type = 'Autotile'
    this.autotile = autotile
    this.isFrames = false
  }
  
  // 通过查找文件,获取Autotile详细信息
  async getDetail (ruleIndex = 0) {
    // 寻找Autotile文件
    const files = await fs.promises.readdir(config.autotilesPath + this.autotile)
    if (!Array.isArray(files) || files.length <= 0) {
      return Promise.reject(utils.error('AUTOTILE_NO_EXISTS', 'Autotile不存在', this.autotile))
    }
    
    // 后缀
    const tail = path.extname(files[0])
    // 如果Autotile有多帧,那么文件数为47 * 4,会大于此值
    const noFrameNum = autotilesOptions.rules.length + 1
    // 构成文件名
    let src = config.autotilesSrcPath + this.autotile + '/' + this.autotile + '_' + autotilesOptions.rules[ruleIndex].name
    // 如果有多帧,再加上帧数前缀
    if (files.length > noFrameNum) {
      // 多帧标识
      this.isFrames = true
      // 构建4帧的动画
      // 构建动画,4帧
      let animationsSrcList = []
      for (let i = 0; i < autotilesOptions.defaultFramesNum; i++) {
        const aniSrc = src + '_' + i + tail
        animationsSrcList.push(aniSrc)
      }
      // 创建默认静置动画
      this.createAnimation(animationsSrcList)
      // 普通显示第一帧图片
      src = src + '_0'
    }
    src = src + tail
    this.src = src
  }
}

module.exports = Autotile